<?php


// 会员管理


namespace app\console\controller;

use app\console\model\MemberCarList;
use think\Build;
use think\Db;
use think\Url;
use think\Loader;
use think\Request;
use think\Controller;
use app\console\model\Member as MemberModel;
use app\console\model\IntegralRecord as IntegralRecordModel;
use app\console\model\MemberWithdraw as MemberWithdrawModel;

class Member extends Controller

{
    /**
     * 认证车辆
     */
    public function car_list($id){
        $data= Db::name('member_car_list')->where('member_id',$id)->order('id desc')->paginate(10);
    return view('',['data' => $data]);
    }

    public function car_list_update($id,Request $request){
        $data = Db::name('member_car_list')->where('id',$id)->find();
        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();
            // 验证

            $data['id_face'] = uploadOne('id_face');
            $data['id_back'] = uploadOne('id_back');
            $data['car_face'] = uploadOne('car_face');
            $data['car_back'] = uploadOne('car_back');

            // 提交数据
            $dispose = (new MemberCarList())->allowField(true)->save($data, ['id' => $id]);
            if ($dispose !== false) {
                ///echo '<script>history.go(-2)</script>';
                //echo "<script language='javascript' type='text/javascript'>history.go(-2)</script>";
                wingo('操作成功', Url::build('car_list'));
            }
            fail('操作失败');

        }
        return view('',['data' => $data]);
    }

    /**
     * @param Request $request
     * @return array|mixed|\think\response\View
     *
     */
    public function car_list_create(Request $request){

        if ($request->instance()->isPost()) {
            $data = $request->instance()->param();
            // 验证
            $car_number = Db::name('member')->where('id',$data['member_id'])->value('car_number');
            if(empty($car_number)){
                fail('会员首次车牌未认证');
            }
            $data['id_face'] = uploadOne('id_face');
            $data['id_back'] = uploadOne('id_back');
            $data['car_face'] = uploadOne('car_face');
            $data['car_back'] = uploadOne('car_back');
            $data['create_time'] = date('Y-m-d H:i:s',time());
            // 提交数据
            $dispose = (new MemberCarList())->allowField(true)->save($data);
            if ($dispose !== false) {
                ///echo '<script>history.go(-2)</script>';
                //echo "<script language='javascript' type='text/javascript'>history.go(-2)</script>";
                wingo('操作成功', Url::build('car_list'));
            }
            fail('操作失败');

        }
        return view('member_car_list_update',[]);
    }

    public function car_list_destory($id,$member_id){
        if (Request::instance()->isGet()) {
            //auding_status($id,'username');

            Db::name('member_car_list')->where('id',$id)->delete();
            win('操作成功', Url::build('car_list',['id' => $member_id]));
        }
        fail('操作失败');
    }


    /**
     * 会员列表
     * @param Request $request
     * @param MemberModel $member
     * @return mixed
     */

    public function index(Request $request, MemberModel $member)

    {

        // 获取参数

        $inquire = $request->instance()->param();


        // 搜索条件

        $condition['id'] = ['gt', 0];

        $condition['is_delete'] = ['eq', 1];
        if (!empty($inquire['is_certification'])) $condition['is_certification'] = ['eq', $inquire['is_certification']];
        if (!empty($inquire['status'])) $condition['status'] = ['eq', $inquire['status']];
        if (!empty($inquire['title'])) $condition['username|car_number|car_name|engine_number|brand_number|phone|car_number|car_model|nickname'] = ['like', '%' . $inquire['title'] . '%'];
        if (!empty($inquire['shop_id'])) $condition['shop_invite_id'] = ['eq', $inquire['shop_id']];
        if (!empty($inquire['interval_timer'])) {
            $interval_timer = explode(' / ', $inquire['interval_timer']);
            $condition['create_time'] = ['between time', [strtotime($interval_timer[0]), strtotime($interval_timer[1])]];
        }


        // 获取会员列表

        $data = $member->where($condition)->order('id', 'desc')->paginate(10, false, ['query' => $inquire])->each(function ($item, $key) {
            if (session('role_id') != 1) {
                $item->username = hideStr($item->username, 1, 6);
            }
        });


        return $this->fetch('index', [
            "mate_title" => '会员列表',
            'data' => $data

        ]);


    }


    /**
     * @param $id
     * @return array
     * 根据ID查询
     */
    public function ajax($id)
    {
        $data = Db::name('member')->where('id', $id)->value('is_certification');
        $car_number = Db::name('member')->where('id', $id)->value('car_number');
        return ['is_certification' => $data, 'car_number' => $car_number];
    }

    public function ajaxTitle()
    {
        $title = Request::instance()->param('title');
        $username = Db::name('member')->where('username|car_number','like',"%".$title."%")->value('username');
        return $username;
    }

    public function title()
    {
        $title = Request::instance()->param('title');
        $username = Db::name('member')->where('username|car_number','like',"%".$title."%")->select()->toArray();
		foreach ($username as $k => &$v){
		    if(session('role_id') != 1){
		        //$v['username'] = hideStr($v['username'],1,6);
		    }
		}
		
		
        return view('',['data' => $username]);
    }

    /**
     * @return array
     * 会员和车牌都修改
     */
    public function car_number()
    {
        $param = Request::instance()->param();
        $member_car = Db::name('member')->where('id', $param['id'])->value('car_number');
        if(empty($member_car)){ //如果会员车牌是空 那就给他绑定车牌 如果不为空
            $ret = Db::name('member')->where('id', $param['id'])->setField('car_number', $param['car_number']);
        }
        if (isset($param['order_id'])) Db::name('order')->where('id', $param['order_id'])->setField('car_number', $param['car_number']);
            return ['code' => 200, 'message' => '修改成功'];
    }

    /**
     * @return array
     * 只修改订单
     */
    public function car_number2()
    {
        $param = Request::instance()->param();
//        halt($param);
        if (isset($param['order_id'])) $ret = Db::name('order')->where('id', $param['order_id'])->setField('car_number', $param['car_number']);
        if ($ret !== false) {
            return ['code' => 200, 'message' => '修改成功'];
        } else {
            return ['code' => 400, 'message' => '修改失败'];
        }

    }


    /**
     * 新增会员
     * @param Request $request
     * @param MemberModel $member
     * @return mixed
     */

    public function create(Request $request, MemberModel $member)

    {


        if ($request->instance()->isPost()) {


            $data = $request->instance()->param();

            $data['create_time'] = strtotime($data['create_time']);

            // 验证

            $validate = Loader::validate('Member');

            if (!$validate->scene('create')->check($data)) fail($validate->getError());


            // 提交数据

            $dispose = $member->allowField(true)->save($data);


            if ($dispose) {

                win('操作成功', Url::build('Member/index'));

            }


            fail('操作失败');


        }


        return $this->fetch('create', [

            "mate_title" => '会员添加',

        ]);


    }

    public function goods_export(Request $request, MemberModel $member){
        // 获取参数

        $inquire = $request->instance()->param();

        $condition['is_delete'] = ['eq', 1];
        if (!empty($inquire['status'])) $condition['status'] = ['eq', $inquire['status']];
        if (!empty($inquire['title'])) $condition['username|car_number'] = ['like', '%' . $inquire['title'] . '%'];
        if (!empty($inquire['shop_id'])) $condition['shop_invite_id'] = ['eq', $inquire['shop_id']];
        if (!empty($inquire['interval_timer'])) {
            $interval_timer = explode(' / ', $inquire['interval_timer']);
            $condition['m.create_time'] = ['between time', [strtotime($interval_timer[0]), strtotime($interval_timer[1])]];
        }
        $data = Db::name('member')
            ->where($condition)
            ->alias('m')
            ->join('manager mr','m.salesman_id = mr.id','left')
            ->field('m.*,mr.nickname mrnickname')
            ->select()->toArray();
            
        foreach ($data as $k => &$v){
        
       
        
            if(session('role_id') != 1){
                $v['username'] = hideStr($v['username'],1,6);
            }
            switch ($v['sex']){
                case 0;
                $v['sex'] = '男';
                break;
                case 1;
                    $v['sex'] = '女';
                    break;
            }
            switch ($v['is_certification']){
                case 1;
                    $v['is_certification'] = '未验证';
                    break;
                case 2;
                    $v['is_certification'] = '等待验证';
                    break;
                case 3;
                    $v['is_certification'] = '已验证';
                    break;
            }
            $v['id_number'] = (string)$v['id_number'];
            switch ($v['level']){
                case 0;
                    $v['level'] = '无';
                    break;
                case 1;
                $v['level'] = '一级';
                break;
                case 2;
                    $v['level'] = '二级';
                    break;
                case 3;
                    $v['level'] = '三级';
                    break;
                case 4;
                    $v['level'] = '四级';
                    break;
                case 5;
                    $v['level'] = '五级';
                    break;
            }
        }
        $this->push($data,'会员信息导出');
    }

    public function push($data, $name = 'Excel')

    {

        set_time_limit(0);

        ini_set('memory_limit', '1024M');

        error_reporting(E_ALL);

        date_default_timezone_set('Asia/Shanghai');



        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');

        $objPHPExcel = new \PHPExcel();



        /*以下是一些设置 ，什么作者  标题啊之类的*/

        $objPHPExcel->getProperties()->setCreator("管理员")

            ->setLastModifiedBy("管理员")

            ->setTitle("电话本导出")

            ->setSubject("数据EXCEL导出")

            ->setDescription("备份数据")

            ->setKeywords("excel")

            ->setCategory("result file");

        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', '我的上级')
            ->setCellValue('B1', '会员id')
            ->setCellValue('C1', '用户账号')
            ->setCellValue('D1', '用户名')
            ->setCellValue('E1', '真实姓名')
            ->setCellValue('F1', '性别')
            ->setCellValue('G1', '会员等级')
            ->setCellValue('H1', '身份证号')
            ->setCellValue('I1', '是否验证')
            ->setCellValue('J1', '车牌号')
            ->setCellValue('K1', '车型')
            ->setCellValue('L1', '识别码')
            ->setCellValue('M1', '注册日期')
            ->setCellValue('N1', '检测报废期')
            ->setCellValue('O1', '机动车强险承保日期')
            ->setCellValue('P1', '机动车商业险承保日期')
            ->setCellValue('q1', '创建时间')
        ;


        $sheet1 = [];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(

                        'bold' => true

                    ),
                    'alignment' => array(

                        'horizontal' =>

                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER

                    )

                )

            );

        }



        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/



        $n = 0;

        foreach ($data as $v) {



            $num = $n + 2;
            $car_number = empty($v['car_number']) ? '' : '('.$v['car_number'].')';
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num,$v['mrnickname'] )
                ->setCellValue('B' . $num, $v['id'])
                ->setCellValue('C' . $num, "\t".$v['username']."\t")
                ->setCellValue('D' . $num, $v['nickname'])
                ->setCellValue('E' . $num, $v['real_name'])
                ->setCellValue('F' . $num, $v['sex'])
                ->setCellValue('G' . $num, $v['level'])
                ->setCellValue('H' . $num, "\t".$v['id_number']."\t")
                ->setCellValue('I' . $num, $v['is_certification'])
                ->setCellValue('J' . $num, $v['car_number'])
                ->setCellValue('K' . $num, $v['car_model'])
                ->setCellValue('L' . $num, $v['id_code'])
                ->setCellValue('M' . $num, $v['register_time'])
                ->setCellValue('N' . $num, $v['test_time'])
                ->setCellValue('O' . $num, $v['destory_time'])
                ->setCellValue('P' . $num, $v['car_business_time'])
                ->setCellValue('Q' . $num,$v['create_time'] )
            ;






            $n++;

        }



        $objPHPExcel->getActiveSheet(0)->setTitle('会员信息导出');

        $objPHPExcel->setActiveSheetIndex(0);



        ob_end_clean();

        header('Content-Type: application/vnd.ms-excel');

        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');

        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

        $objWriter->save('php://output');
        exit;
    }


    public function update($id, Request $request, MemberModel $member)
    {

        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();
            // 验证

            $data['id_face'] = uploadOne('id_face');
            $data['id_back'] = uploadOne('id_back');
            $data['car_face'] = uploadOne('car_face');
            $data['car_back'] = uploadOne('car_back');

            $sqlis_certification = Db::name('member')->where('id',$id)->value('is_certification');
            if($sqlis_certification == 2 && $data['is_certification'] != 2){
                //fail('会员已实名认证通过了');
            }
            if($data['is_certification'] == 2 && ($sqlis_certification == 3 || $sqlis_certification == 1)){
                (new \app\index\controller\Coupon())->send(4, $id);
            }
            // 提交数据
            $dispose = $member->allowField(true)->save($data, ['id' => $id]);
            if ($dispose !== false) {
                ///echo '<script>history.go(-2)</script>';
                //echo "<script language='javascript' type='text/javascript'>history.go(-2)</script>";
                wingo('操作成功', Url::build('Member/index'));
            }
            fail('操作失败');

        }


        $data = $member::get($id);
        (new \app\index\controller\Member())->get_car_qrcode($id);

        $data['distribution_id'] = Db::name('member_distribution')->where(['referrals_id' => $id])->value('distribution_id');

        $data['salesman_id'] = Db::name('share_member')
            ->where('member_id',$id)->value('manage_id');
        if(is_null($data['salesman_id'])) $data['salesman_id'] = 0;
        $salesman = Db::name('salesman s')
            ->join('manager m','s.manage_id = m.id','left')
            ->field('m.username,m.nickname,m.create_time,s.*,m.id,m.telephone')
            ->where('m.level',4)
            ->select()->toArray();

        $salesman_list = \think\Cache::get('salesman_list');
        if(empty($salesman_list)){
            $salesman = getMenuTree2($salesman,0);
        }else{
            $salesman = \think\Cache::get('salesman_list');
        }

        $shop_list = Db::name('shop')->where('auding_status',2)->where('is_delete',1)->select();
        return $this->fetch('create', [
            "mate_title" => '会员编辑',
            'data' => $data,
            'shop_list' => $shop_list,
            'salesman' => $salesman
        ]);

    }



    public function destory($id)
    {

        if (Request::instance()->isGet()) {
            //auding_status($id,'username');
            Db::name('member')->where('id',$id)->delete();
         
            Db::name('share_member')->where('member_id',$id)->delete();
            win('操作成功', Url::build('index'));
        }
        fail('操作失败');

    }




    public function informations($id,MemberModel $shopGoods)
    {
//xiaji
        $info = (new MemberModel())->where('id', $id)->find();



        $inquire = Request::instance()->param();


        // 搜索条件


        $condition['hierarchy'] = ['like', '%,' . $inquire['id'] . ',%'];

        if (!empty($inquire['status'])) $condition['level'] = ['eq', $inquire['status']];

        if (!empty($inquire['title'])) $condition['username'] = ['like', '%' . $inquire['title'] . '%'];


        $data = Db::view('member_distribution', 'id,distribution_id,referrals_id,level,create_time')
            ->view('member', 'username,name,nickname', 'member.id=member_distribution.referrals_id')
            ->where($condition)->order('id', 'desc')->paginate(100, false, ['query' => $inquire]);
        if(Request::instance()->isPost()){
            $dispose = $shopGoods->allowField(true)->save($inquire, ['id' => $id]);
            if ($dispose !== false) {
                win('操作成功', Url::build('index'));
            }
            fail('操作失败');
        }

        return $this->fetch('', [

            "mate_title" => '会员编辑',

            'item' => $info,
            'data' => $data



        ]);

    }

    public function information($id,MemberModel $shopGoods)

    {
//上级会员
        $info = (new MemberModel())->where('id', $id)->find();



        $inquire = Request::instance()->param();


        // 搜索条件


        $condition['hierarchy'] = ['like', '%,' . $inquire['id'] . ',%'];

        if (!empty($inquire['status'])) $condition['level'] = ['eq', $inquire['status']];

        if (!empty($inquire['title'])) $condition['username'] = ['like', '%' . $inquire['title'] . '%'];


        $data = Db::view('member_distribution', 'id,distribution_id,referrals_id,level,create_time')
            ->view('member', 'username,name,nickname,is_vip', 'member.id=member_distribution.referrals_id')
            ->where($condition)->order('id', 'desc')->select()->toArray();
        $member_id_str = Db::name('member')->where('member_id','neq',0)->select();//有效推荐的会员
        $member_id_array = Db::name('member')->where('member_id','eq',0)->select();//有效推荐的会员
        $t_member_list = [];
        $t_member_list_all = [];
        foreach ($member_id_str as $k => $v){
            $t_member_list_all = array_merge($t_member_list_all,explode(',',$v['member_id']));
            if($v['id'] == $id) continue;
            $t_member_list = array_merge($t_member_list,explode(',',$v['member_id']));
        }

        if(Request::instance()->isPost()){
            $member_id_array = Db::name('member')->column('member_id');
            foreach ($member_id_array as $k => $v){
                if(in_array($id,explode(',',$v)) && $info['is_vip'] == 2 && $inquire['is_vip'] == 1){//是推荐来的
                    fail('推荐来的股东，请推荐修改');
                }
            }
            $dispose = $shopGoods->allowField(true)->save($inquire, ['id' => $id]);
            if ($dispose !== false) {
                win('操作成功', Url::build('index'));
            }
            fail('操作失败');
        }
        $member_id_array = Db::name('member')->value('member_id');


        $member_str =(implode(',',$t_member_list));//所有推荐的会员在转成字符串
//        dump($info['member_id']);
//        dump($member_str);
        //if(strpos($member_str,$info['member_id']) !== false){  echo '包含jb51'; }else{ echo '不包含jb51'; }
        $member_list = $data;
        return $this->fetch('', [
            'member_str' => $member_str,
            'array_m' => $t_member_list,
            'array_m_all' => $t_member_list_all,
            'member_list' => $member_list,
            "mate_title" => '会员编辑',
            'item' => $info,
            'data' => $data



        ]);

    }


    // 会员充值
    public function recharge()
    {
        $model = new MemberModel();
        $withdraw_model = new MemberWithdrawModel();
        $uid = Request::instance()->param('uid');

        $item = $model->where('id', $uid)->field('id,balance,username')->find();

        if (Request::instance()->isPost()) {
            // 获取数据
            $data = Request::instance()->post();

            Db::startTrans();

            try {
                $amount = $model->where(['id' => $data['id']])->value('balance');

                // 生成订单号
                $order_number = $this->createNumber();
                // 展示数据
                $information = [
                    'type_id'      => '1',
                    'member_id'    => $data['id'],
                    'balance'      => ($amount + $data['price']),
                    'price'        => $data['price'],
                    'way'          => '后台充值',
                    'status'       => '1',
                    'order_number' => $order_number,
                    'create_time'  => time()
                ];

                // 添加成功
                $result = $withdraw_model->save($information);

                Db::name('member')->where('id', $data['id'])->setInc('balance', $data['price']);

                Db::commit();

                return ['code' => 200, 'message' => 'OK'];

            } catch (\Exception $e) {

                //回滚事务
                Db::rollback();
                return ['code' => 0, 'message' => $e->getMessage()];
            }


        }


        return $this->fetch('', [
            'mate_title' => '会员充值',
            'data'       => $item,
        ]);
    }


    // 积分充值
    public function integral()
    {
        // 获取数据
        $user_id = Request::instance()->param('uid');

        // 模型实例化
        $model = new MemberModel();

        // 获取数据
        $data = $model->where('id', $user_id)->field('integral,username,id')->find();

        if (Request::instance()->isPost()) {

            Db::startTrans();

            try {
                // 获取数据
                $data = Request::instance()->param();

                Db::name('integral_record')->insert(
                    [
                        'member_id'   => $data['id'],
                        'type_id'     => '1',
                        'type'        => '后台充值',
                        'integral'    => $data['price'],
                        'title'       => '后台充值积分',
                        'create_time' => time()
                    ]

                );

                Db::name('member')->where('id', $data['id'])->setInc('integral', $data['price']);

                //回滚事务
                Db::commit();
                return ['code' => 200, 'message' => 'OK'];

            }catch (\Exception $e) {

                //回滚事务
                Db::rollback();
                return ['code' => 0, 'message' => $e->getMessage()];
            }
        }



        return $this->fetch('', [
            'mate_title' => '积分充值',
            'data'       => $data
        ]);
    }


    /*
    * 启用状态改变
    */
    public function auditing()
    {
        $id = Request::instance()->param('id');
        $status = MemberModel::where('id', $id)->value('status') == '1' ? 2 : 1;
        if (MemberModel::where('id', $id)->update(['status' => $status])) {
            return $status;
        }
        return false;
    }


    /*

    * 会员分销

    */

    public function distribution()

    {

        // 获取参数

        $inquire = Request::instance()->param();


        // 搜索条件


        $condition['hierarchy'] = ['like', '%,' . $inquire['id'] . ',%'];

        if (!empty($inquire['status'])) $condition['level'] = ['eq', $inquire['status']];

        if (!empty($inquire['title'])) $condition['username'] = ['like', '%' . $inquire['title'] . '%'];


        $data = Db::view('member_distribution', 'id,distribution_id,referrals_id,level,create_time')
            ->view('member', 'username,name,nickname', 'member.id=member_distribution.referrals_id')
            ->where($condition)->order('id', 'desc')->paginate(10, false, ['query' => $inquire]);
        $memberlevel_select = Db::name('member_distribution')->field('distinct level')->select();
        return $this->fetch('distribution', [
            'memberlevel_select' => $memberlevel_select,
            "mate_title" => $inquire['id'] . ' - TA的分销列表',

            'data' => $data

        ]);


    }

    protected function createNumber()
    {
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

        return $order_id;
    }

}